/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufms.facom.locadora.ws;

import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.view.Results;
import br.ufms.facom.locadora.ws.dao.ItemDao;
import br.ufms.facom.locadora.ws.exception.InternalServerErroException;
import br.ufms.facom.locadora.ws.exception.WebServiceException;
import java.io.*;


/**
 *
 * @author jairo_filho
 */
@Resource
public class FilmeController {
    
    private ItemDao itens;
    private Result result;

    public FilmeController(ItemDao itens, Result result) {
        this.itens = itens;
        this.result = result;
    }
    
    @Get("/item/{id}/situacao")
    public void consultarSituacaoDoItem(String id) {
        
        try {
        
        SituacaoDeUmItem situacao = itens.consultarSituacaoDeUmItem(id);
        
        result.use(Results.json()).withoutRoot().from(situacao).serialize();
        
        }
        
        catch(WebServiceException ex) {
            handle(ex);
        }
        
        catch(Throwable ex) {
            
            InternalServerErroException wsex = 
                new InternalServerErroException(
                    "Problemas internos no processamento da requisição!" + 
                    "Informe o administrador do sistema!", ex);
            
            handle(wsex);
        }
    }

    private void handle(WebServiceException ex) {
        
        result.use(Results.http()).setStatusCode(ex.getHttpStatusCode());
        result.use(Results.json()).withoutRoot().from(new Error(ex)).exclude("techMsg").serialize();
        
        log(ex);
    }

    private void log(Exception exception) {
        try {
            
            FileWriter fw = new FileWriter ("last_error.txt", true);
            PrintWriter pw = new PrintWriter (fw);
            exception.printStackTrace(pw);
        
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}
